//
//  ST_FateAlertManager.swift
//  btvideo
//
//  Created by mac on 2020/12/30.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyUserDefaults

class ST_FateAlertManager: NSObject {
    
    static let shared = ST_FateAlertManager()
    // Can't init is singleton
    private override init() {
        super.init()
    }
    
    fileprivate weak var gift_toast_controller:UIViewController?
    
    fileprivate weak var fate_toast_controller:UIViewController?
    
    fileprivate weak var talk_fate_toast_controller:UIViewController?
    
    fileprivate var toastStep = 0
    
    fileprivate var step_past_set = Set<Int>()
    
//    MARK: - Private Method
    fileprivate func fate_account_key()->String{
        
//        return UUID().uuidString
        
        let key = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.accid ?? UUID().uuidString

        return "myDateToday_"+key+"28943849"
    }
    
    /**
     今日缘分 不需要展示
     */
    fileprivate func fate_unexpended()->Bool{
        
        if step_past_set.contains(toastStep){
            return true
        }
        
        if let lastDate = Defaults.date(forKey: fate_account_key()){
            
            #if DEBUG
            //            有值 并且超过4分钟
            if lastDate.timeIntervalSinceNow.abs < 2*60{
                return true
            }
            #else
            //            有值 并且是今天
            if lastDate.isInToday{
                return true
            }
            #endif
        }
        
        return false
        
    }
    
    
    fileprivate func media_talk_fate_unexpended()->Bool{
        
        if step_past_set.contains(toastStep){
            return true
        }
        
        if let lastDate = Defaults.date(forKey: media_talk_fate_account_key()){
            
            #if DEBUG
            //            有值 并且超过4分钟
            if lastDate.timeIntervalSinceNow.abs < 2*60{
                return true
            }
            #else
            //            有值 并且是今天
            if lastDate.isInToday{
                return true
            }
            #endif
        }
        
        return false
        
    }
    
    
    fileprivate func media_talk_fate_account_key()->String{
        
        let key = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.accid ?? UUID().uuidString
        
        return key + "_toastTodayMediaTalkFate"
    }
    
    fileprivate var media_talk_alert_timer:Timer?
    
    fileprivate var media_talk_alert_times:Int?
    
    fileprivate func next_media_talk_fate_toast(){
        
        
        self.media_talk_alert_timer?.invalidate()
        self.media_talk_alert_timer = nil
        
        
        
        if let times = self.media_talk_alert_times,let itemJson = SC.toast_fate_chat_config.arrayValue[safe: times] {
            
            let seconds = itemJson["time"].intValue
            
            self.media_talk_alert_timer  = Timer.scheduledTimer(timeInterval: TimeInterval(seconds), target: self, selector: #selector(ST_FateAlertManager.media_talk_fate_toast), userInfo: nil, repeats: false)
            
            self.media_talk_alert_times = times + 1
            
        }else{
            
            self.media_talk_alert_times = nil
        }
    }
    
    @objc fileprivate func media_talk_fate_toast(){
        
        if  ST_DTBootManager.shared.isDisplayLoginKeyWindow {
            self.media_talk_alert_times = nil
            return
        }
        
        next_media_talk_fate_toast()
        
        let status = ST_BTUserInfoManager.shared.app_chat_status_behavior.value
//        不是忙碌 并且 不是在弹窗状态
        if talk_fate_toast_controller == nil && status.rawValue < 3{
            
            
            JVrequest(PH.getRecommendOneApi) { (json) in
                
                ST_MediaChatDispatcher.shared.live_alert_accid_set.update(with: json["data"]["accid"].stringValue)
                
                let vc = CupidFactory.currency(for: json["data"], cupidType: .recommendSomeOne)
                
//                let vc = ST_EnjoyCupidViewController()
//
//                vc.overCurrentContext = true
//
//                vc.over_current_context_alpha = "0.8"
//
//                vc.type = .recommendSomeOne
//
////                vc.firstModel = ST_LiveBeautyCellModel.init(fromJson: json["data"])
//
//                vc.json = json["data"]
                
                self.talk_fate_toast_controller = vc
                
                GlobalPresent(toController: vc)
                
            } failure: { (code, err) in
                
            }

            
            
            
            step_past_set.update(with: 2)
            
            
        }
        
        
 
    }
    
    fileprivate func fateToast(){
        
        if fate_toast_controller != nil {
            return
        }
        
        
        JVrequest(PH.fateNewListApi, success: { (json) in
            
            let data = json["data"]
            
            print("假装今日缘分数据：",json)
            
            var array = [ST_PairsLoveItemViewModel]()
            
            for item in data.arrayValue{
                
                if let model = ST_PairsLoveItemViewModel.deserialize(from: item.dictionaryObject){
                    
                    let albumList = ST_PairsShareParticularModel.describe(json_array: item["album"].arrayValue)
                    
                    model.album = albumList
                    
                    array.append(model)
                }
            }
            
            self.push_today_fate_cards(array: array)
            
        
            
        }) { (code, err) in
            
            self.push_today_fate_cards()
        }
    }
    
    fileprivate func push_today_fate_cards(array:[ST_PairsLoveItemViewModel]? = nil){
        
        guard let list = array,list.count > 0 else {
            
            self.toastStep = 2
            
            self.dispatch()
            
            return
        }
        
        
        let vc = ST_TodayFateCardsController()
        
        vc.overCurrentContext = true
        
        fate_toast_controller = vc
        
        vc.cards_array = list
        
        GlobalPresent(toController: vc)
        
        step_past_set.update(with: 1)
        
        
    }
    
    
    fileprivate func requsetLoginReward() {
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
            
            self.toastStep = 1
            
            dispatch()
            
            return
        }
        
        
        JVrequest(PH.loginRewardApi, success: { (json) in
                      
            
            print("今日缘分打印：",json)
            
            if ST_DTBootManager.shared.isDisplayLoginKeyWindow{
                return
            }
            
            if json["data"].dictionaryValue.keys.count < 1{
                
                self.toastStep = 1
                
                self.dispatch()
                
                return
            }
            
            let alert = ST_LoginForGiftController()
            
            alert.json = json
            
            alert.overCurrentContext = true
            
            alert.over_current_context_alpha = "0.4"
            
            self.toastStep = 1
            
            self.gift_toast_controller = alert
         
            GlobalPresent(toController: alert, animated: false)
            
        }) { (code, err) in
            
            print("今日缘分错误：",err)
        }
        
    }
    
//    MARK: - Public Method
    func setCurrentAccountFateState(isFinish:Bool)  {
        
        if isFinish {
            
            Defaults.setValue(Date(), forKey: fate_account_key())
            
        }else{
            
            Defaults.removeObject(forKey: fate_account_key())
            
        }
    }
    
    func setCurrentAccountMediaTalkFateState(isFinish:Bool)  {
        
        if isFinish {
            
            Defaults.setValue(Date(), forKey: media_talk_fate_account_key())
            
        }else{
            
            Defaults.removeObject(forKey: media_talk_fate_account_key())
            
        }
    }
  
    func dispatch(revert:Bool = false)  {
        
        if revert {
            toastStep = 0
            step_past_set.removeAll()
        }
        
        switch toastStep {
        case 0:
            requsetLoginReward()
        case 1:
            
//            男才有 今日缘分
            if fate_unexpended() || ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female {
                
                self.toastStep = 2
                dispatch()
                
                return
            }
            
            fateToast()
        case 2:
            
//            if media_talk_fate_unexpended(){
//                self.toastStep = 3
//                return
//            }
            
            self.media_talk_alert_times = 1
            media_talk_fate_toast()
            
        default:
            
            break
        }
    }
    
    
    
    
    
}
